#include "MqUtil.h"

using namespace std;
using namespace AmqpClient;

MqProducer::MqProducer(const string &uri, const string &exchange, const string &routingKey)
{
    m_mconf.exchange = exchange;
    m_mconf.routingKey = routingKey;

    m_Channel = Channel::CreateFromUri(uri);
}

bool MqProducer::PutMsg(const string &msg)
{
    BasicMessage::ptr_t message = BasicMessage::Create(msg);

    if (!message || !m_Channel)
    {
#ifdef DEBUG
        cout << "[ERROR] " << "message or channel is empty!" << endl;
#endif
        return false;
    }

    m_Channel->BasicPublish(m_mconf.exchange, m_mconf.routingKey, message);

    return true;
}

MqConsumer::MqConsumer(const string &uri, const string &queue)
{
    m_mconf.queue = queue;
    m_Channel = Channel::CreateFromUri(uri);
}

string MqConsumer::GetMsg()
{
    if (!m_Channel)
    {
#ifdef DEBUG
        cout << "[ERROR] " << "channel is empty!" << endl;
#endif
        return "";
    }

    Envelope::ptr_t envelope = m_Channel->BasicConsumeMessage();
    if (envelope && envelope->Message())
    {
        string Outmsg = envelope->Message()->Body();
#ifdef DEBUG
        cout << "[DEBUG] " << Outmsg << " -----> consumer" << endl;
#endif
        return Outmsg;
    }
    else
    {
#ifdef DEBUG
        cout << "[ERROR] " << "envelope is empty!" << endl;
#endif
        return "";
    }
}

void MqConsumer::ConsumeLoop(ConsumeCallback_t ConsumeCallback)
{
    if(!m_Channel)
    {
#ifdef DEBUG
        cout << "[ERROR] " << "m_Channel is empty!" << endl;
#endif
    }

    m_Channel->BasicConsume(m_mconf.queue);
    
    for(;;)
    {
        string path = GetMsg();
        if(path.empty())
        {
#ifdef DEBUG
            cout << "[ERROR] " << "path is empty!" << endl;
#endif
            return;
        }

        if(!ConsumeCallback(path))
        {
#ifdef DEBUG
            cout << "[ERROR] " << "upload error about callback!" << endl;
#endif
            return;
        }
    }
}